package ldh.im.fxgui.component;

import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.ListView;
import javafx.scene.layout.Pane;
import ldh.im.fxbase.cell.ObjectListCell;
import ldh.im.fxbase.util.RegionUtil;
import ldh.im.fxgui.controller.MItemController;
import ldh.im.fxbase.pojo.ImGroup;

import java.util.WeakHashMap;

public class MessageListView extends ListView<ImGroup> {

    private WeakHashMap<String, Node> weakHashMap = new WeakHashMap<String, Node>();

    public MessageListView() {
        super();
        init();
    }

    public MessageListView(ObservableList<ImGroup> items) {
        super(items);
        init();
    }

    public void addItem(ImGroup mItem) {
        this.getItems().add(mItem);
    }

    private void init() {
        this.setCellFactory(new ObjectListCell<>(mItem->{
            String id = mItem.getName();
            Node node = weakHashMap.get(id);
            if (node != null) return node;
            RegionUtil.FxmlBean<Pane, MItemController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/sub/MItemPane.fxml"));
            fxmlBean.getController().setData(mItem);
            weakHashMap.put(id, fxmlBean.getNode());
            return fxmlBean.getNode();
//            return mItem.getName();
        }));
    }
}
